<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\Admin;

use App\Controller\AppBaseController;
use App\Model\Article;
use App\Model\ArticleColumn;

use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\AdminApiAuth;

#[Controller(prefix: 'admin')]
#[Middleware(AdminApiAuth::class)]
class ArticleController extends AppBaseController
{

    /**
     * 后台--专栏栏目列表
     * @return object
     */
    #[RequestMapping(path:'articleColumnList',methods: 'get')]
    public function articleColumnList(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['status'] = 1;
            $list = ArticleColumn::where($where)
                ->selectRaw('id,name,type,status')
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = ArticleColumn::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }

    /**
     * 后台--学专栏栏目详情
     * @param int $column_id
     * @return object
     */
    #[RequestMapping(path:'articleColumnInfo/{column_id}',methods: 'get')]
    public function articleColumnInfo(int $column_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $where['status'] = 1;
            $where['id'] = $column_id;
            $info = ArticleColumn::where($where)->first();
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 专栏栏目发布|编辑
     * @param int|null $column_id
     * @return object
     */
    #[RequestMapping(path: 'articleColumnEdit[/{column_id}]',methods: 'post,get')]
    public function articleColumnEdit(int|null $column_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['name'] = 'xxxxxxx';
//                $data['is_banner'] = 1;
//                $data['banner_photo'] = 'fqxinyi23/test/xyWords/xyWords1691110928830.jpg';
//                $data['status'] = 1;
//            }
            //虚拟数据


            //默认特殊专栏
            $data['type'] = 1;
            if(empty($data['name'])) return $this->reMsg->re(10007);

            empty($data['is_banner']) || !is_numeric($data['is_banner']) ? $data['is_banner'] = 0 : $data['is_banner'] = 1;
            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;

            //指定支部（不指定党支部）
            if($_admin->level==1){
//                if(empty($data['party_id'])) return $this->reMsg->re(10007);
//                $party_id = $data['party_id'];
                $party_id = $_admin->party_id;
            }else{
                $party_id = $_admin->party_id;
            }

            //验证权限（超级管理员）
            if($_admin->level!=1) return $this->reMsg->re(10009);

            if($column_id){
                //编辑
                $info = ArticleColumn::where('id',$column_id)->first();
                if(empty($info)) return $this->reMsg->re(10008);
                $info->type = $data['type'];
                $info->name = $data['name'];
                $info->is_banner = $data['is_banner'];
                $info->banner_photo = $data['banner_photo'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                return $this->reMsg->re(1);
            }else{
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                $insertRet = ArticleColumn::create($data);
                if($insertRet){
                    return $this->reMsg->re(1);
                }else{
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 专栏栏目|删除
     * @param int $column_id
     * @return object
     */
    #[RequestMapping(path:'articleColumnDelete/{column_id}',methods: 'get')]
    public function articleColumnDelete(int $column_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = ArticleColumn::where('id',$column_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限（超级管理员）
            if($_admin->level!=1) return $this->reMsg->re(10009);
            //查询该栏目下是否存在 学习天地内容
            $studyList = Article::where('column_id',$column_id)->first();
            if($studyList){
                return $this->reMsg->re(0,'该栏目存在内容，不可删除');
            }
            $info->delete();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--专栏文章列表   type 1：专栏
     * @param int|null $column_id
     * @return object
     */
    #[RequestMapping(path:'articleList[/{column_id}]',methods: 'post,get')]
    public function articleList(int|null $column_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where = [];
            //指定支部
            if($_admin->level==1){
                $party_id = $this->request->input('party_id', null);
                if($party_id){
                    $where['party_id'] = $party_id;
                }
            }else{
                $where['party_id'] = $_admin->party_id;
            }

            if($column_id){
                $where['column_id'] = $column_id;
            }
            $list = Article::with(['party'=>function($query){
                    $query->selectRaw('id,name')->first();
                },'column'=>function($query){
                    $query->selectRaw('id,name')->first();
                }])->where($where)
                ->selectRaw('id,party_id,column_id,title,created_at')
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = Article::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--专栏文章详情
     * @param int $article_id
     * @return object
     */
    #[RequestMapping(path:'articleInfo/{article_id}',methods: 'get')]
    public function articleInfo(int $article_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $info = Article::where('id',$article_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 专栏文章发布|编辑
     * @param int|null $article_id
     * @return object
     */
    #[RequestMapping(path: 'articleEdit[/{article_id}]',methods: 'post,get')]
    public function articleEdit(int|null $article_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['party_id'] = 1;
//                $data['type'] = 1;
//                $data['column_id'] = 1;
//                $data['title'] = '或那个风格二个人哥哥';
//                $data['photo'] = 'fqxinyi23/test/xyWords/xyWords1691110928830.jpg';
//                $data['content'] = '学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习';
//                $data['media_list'] = [
//                    '0'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                    '1'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                ];
//                $data['file_list'] = [
//                    '0'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                    '1'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                ];
//                $data['link_url'] = 'https://www.baidu.com';
//                $data['is_long'] = 0;
//                $data['show_start_at'] = '2024-09-01 12:12:12';
//                $data['show_end_at'] = '2024-09-01 12:12:12';
//                $data['status'] = 1;
//            }
            //虚拟数据

            if(empty($data['column_id']) || !is_numeric($data['column_id'])
                || empty($data['title'])
            ) return $this->reMsg->re(10007);

            if(empty($data['photo'])) $data['photo'] = null;
            if(empty($data['content'])) $data['content'] = null;
            if(empty($data['link_url'])) $data['link_url'] = null; //增加外部链接
            if(empty($data['media_list']) || !is_array($data['media_list'])) $data['media_list'] = [];
            if(empty($data['file_list']) || !is_array($data['file_list'])) $data['file_list'] = [];
            if(isset($data['is_long']) && $data['is_long']==0){
                if(empty($data['show_start_at']) || empty($data['show_end_at'])) return $this->reMsg->re(10007);
            }else{
                $data['is_long'] = 1;
                $data['show_start_at'] = null;
                $data['show_end_at'] = null;
            }
            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;

            //指定支部
            if($_admin->level==1){
//                if(!isset($data['party_id']) || $data['party_id']==null) return $this->reMsg->re(10007);
//                $party_id = $data['party_id'];
                $party_id = $_admin->party_id;
            }else{
                $party_id = $_admin->party_id;
            }

            if($article_id){
                //编辑
                $info = Article::where('id',$article_id)->first();
                if(empty($info)) return $this->reMsg->re(10008);

                //判断是否有权操作
                if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);

//                $info->column_id = $data['column_id'];
                $info->title = $data['title'];
                $info->content = $data['content'];
                $info->link_url = $data['link_url'];
                $info->media_list = $data['media_list'];
                $info->file_list = $data['file_list'];
                $info->is_long = $data['is_long'];
                $info->show_start_at = $data['show_start_at'];
                $info->show_end_at = $data['show_end_at'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                return $this->reMsg->re(1);
            }else{
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                $insertRet = Article::create($data);
                if($insertRet){
                    return $this->reMsg->re(1);
                }else{
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 专栏文章|删除
     * @param int $article_id
     * @return object
     */
    #[RequestMapping(path:'articleDelete/{article_id}',methods: 'get')]
    public function articleDelete(int $article_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = Article::where('id',$article_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限
            if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);
            $info->delete();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }





}